<script setup lang="ts">
import { createConsultOrder, getConsultOrderPre } from '@/services/consult'
import { getPatientDetail } from '@/services/user'
import { useConsultStore } from '@/stores'
import type { ConsultOrderPreData } from '@/types/consult'
import type { Patient } from '@/types/user'
import { showConfirmDialog, showDialog, showToast } from 'vant'
import { onMounted, ref } from 'vue'
import { onBeforeRouteLeave, useRouter } from 'vue-router'

const store = useConsultStore()
// 订单支付信息
const payInfo = ref<ConsultOrderPreData>()
const loadPayInfoData = async () => {
  const res = await getConsultOrderPre({
    type: store.consult.type,
    illnessType: store.consult.illnessType
  })
  payInfo.value = res.data // 赋值
  store.setCouponId(res.data.couponId as string) // 设置默认优惠券
}
/* 患者信息 */
const patient = ref<Patient>()
const loadPatient = async () => {
  if (!store.consult.patientId) return
  const res = await getPatientDetail(store.consult.patientId)
  patient.value = res.data
}
onMounted(() => {
  // 防止页面刷新时,本地数据已清空 -> 跳转首页
  if (
    !store.consult.type ||
    !store.consult.illnessType ||
    !store.consult.depId ||
    !store.consult.patientId
  ) {
    return showDialog({
      title: '温馨提示',
      message: '请重新输入问诊病例',
      closeOnPopstate: false
    }).then(() => {
      return router.push('/')
    })
  }
  loadPayInfoData()
  loadPatient()
})

// 生成订单,展开 支付方式抽屉
const show = ref(false) // 抽屉
const agree = ref(false) // 勾选协议
const orderId = ref<string>() // 订单id
const loading = ref(false)
// const paymentMethod = ref<'0' | '1'>() // 支付方式 0支付宝 1微信
const openShow = async () => {
  if (!agree.value) return showToast('请勾选用户支付协议')
  loading.value = true
  // 生成问诊订单
  const res = await createConsultOrder(store.consult)
  orderId.value = res.data.id
  loading.value = false
  //  store.clear() // 清空问诊记录
  // 打开支付抽屉
  show.value = true
}
// 进行支付
// 1.隐藏抽屉的关闭按钮
// 2.再关闭抽屉的时候 弹出确认框 仍要关闭>订单页面 继续支付>关闭确认框
// 3.生成订单的时候回退 拦截
// 4.生成支付地址然后跳转: 掉后台接口
// 5.刷新页面的时候,判断是否问诊记录是否存在,不存在就alert提示,确认之后回到首页
const router = useRouter()
const onClose = () => {
  return showConfirmDialog({
    title: '温馨提示',
    message: '取消支付将无法获得医生回复,医生接诊名额有限,是否确认关闭?',
    cancelButtonText: '仍要关闭',
    confirmButtonText: '继续支付',
    confirmButtonColor: 'var(--cp-primary)'
  })
    .then(() => {
      // (确定)继续支付,关闭确认框
      return false
    })
    .catch(() => {
      // (取消)仍要关闭 去订单页面
      orderId.value = ''
      router.push('/user/consult')
      return true
    })
}
// 1.对已生成的订单,回退进行拦截
// 2.并且清空 问诊记录
onBeforeRouteLeave(() => {
  if (orderId.value) return false // 拦截在当前页面
})
</script>

<template>
  <!-- 顶部标题 -->
  <div class="consult-pay-page" v-if="payInfo && patient">
    <cp-nav-bar title="支付" />
    <!-- 支付标题 -->
    <div class="pay-info">
      <p class="tit">图文问诊 {{ payInfo?.actualPayment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>

    <!-- 支付信息 -->
    <van-cell-group>
      <van-cell
        title="优惠券"
        :value="
          payInfo.couponDeduction === 0
            ? '暂无'
            : `-¥${payInfo.couponDeduction}`
        "
      />
      <van-cell
        title="积分抵扣"
        :value="
          payInfo.pointDeduction === 0
            ? '不可抵扣'
            : `-¥${payInfo.pointDeduction}`
        "
      />
      <van-cell
        title="实付款"
        :value="`¥${payInfo.payment}`"
        class="pay-price"
      />
    </van-cell-group>
    <div class="pay-space"></div>

    <!-- 患者信息 -->
    <van-cell-group>
      <van-cell
        title="患者信息"
        :value="`${patient.name} | ${patient.genderValue} | ${patient.age}岁`"
      ></van-cell>
      <van-cell title="病情描述" :label="store.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="agree"
        >我已同意 <span class="text">支付协议</span></van-checkbox
      >
    </div>

    <!-- 支付按钮 -->
    <van-submit-bar
      button-type="primary"
      :price="payInfo.actualPayment * 100"
      button-text="立即支付"
      text-align="left"
      @click="openShow"
      :loading="loading"
    />
    <!-- 支付方式抽屉 -->
    <cp-pay-sheet
      v-model:show="show"
      @update:show="onClose"
      payCallback="/room"
      :actual-payment="payInfo.actualPayment"
      :order-id="orderId as string"
    ></cp-pay-sheet>
  </div>
  <!-- 骨架屏 -->
  <div class="skeleton" v-else>
    <van-skeleton title style="margin-bottom: 16px"></van-skeleton>
    <van-skeleton title avatar avatar-size="42" :row="2" />
    <van-skeleton title :row="3" />
    <van-skeleton title :row="4" />
    <van-skeleton title :row="3" />
  </div>
</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;
}
.pay-info {
  display: flex;
  padding: 15px;
  flex-wrap: wrap;
  align-items: center;
  .tit {
    width: 100%;
    font-size: 16px;
    margin-bottom: 10px;
  }
  .img {
    margin-right: 10px;
    width: 38px;
    height: 38px;
    border-radius: 4px;
    overflow: hidden;
  }
  .desc {
    flex: 1;
    > span {
      display: block;
      color: var(--cp-tag);
      &:first-child {
        font-size: 16px;
        color: var(--cp-text2);
      }
    }
  }
}
.pay-price {
  ::v-deep() {
    .van-cell__title {
      font-size: 16px;
    }
    .van-cell__value {
      font-size: 16px;
      color: var(--cp-price);
    }
  }
}
.pay-space {
  height: 12px;
  background-color: var(--cp-bg);
}
.pay-schema {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  .text {
    color: var(--cp-primary);
  }
}
::v-deep() {
  .van-submit-bar__button {
    font-weight: normal;
    width: 160px;
  }
}
// .pay-type {
//   .amount {
//     padding: 20px;
//     text-align: center;
//     font-size: 16px;
//     font-weight: bold;
//   }
//   .btn {
//     padding: 15px;
//   }
//   .van-cell {
//     align-items: center;
//     .cp-icon {
//       margin-right: 10px;
//       font-size: 18px;
//     }
//     .van-checkbox :deep(.van-checkbox__icon) {
//       font-size: 16px;
//     }
//   }
// }
</style>
